<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <link rel="stylesheet" type="text/css" href="./ico/iconfont.css">
    <link rel="stylesheet" type="text/css" href="./contextjs/css/context.standalone.css">
    <script type="text/javascript" src="./libs/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="./contextjs/js/context.js"></script>
    <script type="text/javascript" src="./libs/d3.min.js"></script>
    <script type="text/javascript" src="./libs/jsplumb.js"></script>
    <style>
        body, ul {
            margin: 0;
            padding: 0;
        }

        .abs {
            position: absolute;
            width: 200px;
            z-index: 10000;
            background-color: rgba(227, 244, 255, .9);
            cursor: move !important;
        }

        .left {
            float: left;
            width: 15%;
        }

        .left ul li {
            list-style-type: none;
            border: 1px solid #289de9;
            border-radius: 15px;
            cursor: pointer;
            line-height: 26px;
            -webkit-touch-callout: none; /* iOS Safari */
            -webkit-user-select: none; /* Chrome/Safari/Opera */
            -khtml-user-select: none; /* Konqueror */
            -moz-user-select: none; /* Firefox */
            -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently not supported by any browser */
            margin: 4px 1px;
            overflow: hidden;
            display: flex;
        }

        .left ul li .iconfont {
            width: 26px;
            height: 26px;
            margin: 1px;
            border-radius: 100%;
        }

        .left ul li .iconfont {
            float: left;
            color: #fff;
            font-size: 23px;
            background-color: #289de9;
        }

        .pDiv {
            float: left;
            width: 83%;
            height: 400px;
            border: 5px solid rgb(255, 0, 0, 0.1);
            overflow-y: scroll;
            position: relative;
            overflow-x: hidden;
        }

        .pane-node-content {

            border: 1px solid #289de9;
            border-radius: 15px;
            cursor: move;
            line-height: 26px;
            overflow: hidden;
            min-width: 150px;

        }

        .pane-node-content:hover {
            background-color: rgba(227, 244, 255, .9);

        }

        .pane-node-content .iconfont {
            width: 26px;
            height: 26px;
            margin: 1px;
            border-radius: 100%;
        }

        .pane-node-content .iconfont {
            float: left;
            color: #fff;
            font-size: 23px;
            background-color: #289de9;
        }

        .mycursor {
            cursor: crosshair;
        }

        .in-hover {
            border: 5px solid rgba(255, 0, 0, .3);
        }

        .hide {
            border: 1px solid red;
        }

        /*.aLabel {
            -webkit-transition: background-color 0.25s ease-in;
            -moz-transition: background-color 0.25s ease-in;
            transition: background-color 0.25s ease-in;
        }

        .aLabel.jtk-hover, .jtk-source-hover, .jtk-target-hover {
            background-color: #1e8151;
            color: white;
        }

        .aLabel {
            background-color: white;
            opacity: 0.8;
            padding: 0.3em;
            border-radius: 0.5em;
            border: 1px solid #346789;
            cursor: pointer;
        }*/

    </style>
</head>
<body>
<div class='left'>
    <ul>
        <li>
            <span class="iconfont icon-dataBase"></span>
            存储过程
        </li>
        <li>
            <span class="iconfont icon-SQLshujuji"></span>
            SQL脚本
        </li>
        <li>
            <span class="iconfont icon-icon-dian"></span>
            类型转换
        </li>
        <li>
            <span class="iconfont icon-jiedianchaifen"></span>
            归一化
        </li>
        <li>
            <span class="iconfont icon-jiedianchaifen"></span>
            拆分
        </li>
        <li>
            <span class="iconfont icon-jiedianchaifen"></span>
            全表统计
        </li>
    </ul>
</div>
<div id="flow-panel" class="pDiv">

</div>
<script>
    jsPlumb.ready(function () {

        var instance = window.jsp = jsPlumb.getInstance({
            // default drag options
            DragOptions: {cursor: 'move', zIndex: 2000},
            // the overlays to decorate each connection with.  note that the label overlay uses a function to generate the label text; in this
            // case it returns the 'labelText' member that we set on each connection in the 'init' method below.
            ConnectionOverlays: [
                ["Arrow", {
                    location: 1,
                    visible: true,
                    width: 11,
                    length: 11,
                    id: "ARROW",
                    events: {
                        click: function () {
                            alert("you clicked on the arrow overlay")
                        }
                    }
                }], /*,
					[ "Label", {
						location: 0.1,
						id: "label",
						cssClass: "aLabel",
						events:{
							tap:function() { alert("hey"); }
						}
					}]*/
            ],
            // ConnectionsDetachable: true,
            Container: "flow-panel"
        });

        var basicType = {
            connector: "StateMachine",
            paintStyle: {stroke: "red", strokeWidth: 4},
            hoverPaintStyle: {stroke: "blue"},
            overlays: [
                "Arrow"
            ]
        };
        instance.registerConnectionType("basic", basicType);

        // this is the paint style for the connecting lines..
        var connectorPaintStyle = {
                strokeWidth: 1,
                stroke: "#888"/*,
					joinstyle: "round",
					outlineStroke: "white",
					outlineWidth: 2*/
            },
            // .. and this is the hover style.
            connectorHoverStyle = {
                strokeWidth: 4,
                stroke: "#999"/*,
					outlineWidth: 5,
					outlineStroke: "white"*/
            },
            endpointHoverStyle = {
                fill: "#999"/*,
					stroke: "#216477"*/
            },
            // the definition of source endpoints (the small blue ones)
            sourceEndpoint = {
                endpoint: "Dot",
                paintStyle: {
                    stroke: "#888",
                    fill: "#fff",
                    radius: 5,
                    strokeWidth: 1
                },
                isSource: true,
                //connector: [ "Flowchart", { stub: [40, 60], gap: 10, cornerRadius: 5, alwaysRespectStubs: true } ],
                connector: ["Bezier", {Bezier: 20}],
                connectorStyle: connectorPaintStyle,
                hoverPaintStyle: endpointHoverStyle,
                connectorHoverStyle: connectorHoverStyle,
                dragOptions: {},
                maxConnections: -1,
                overlays: [
                    ["Label", {
                        location: [0.5, 1.5],
                        label: "Drag",
                        cssClass: "endpointSourceLabel",
                        visible: false
                    }]
                ]
            },
            // the definition of target endpoints (will appear when the user drags a connection)
            targetEndpoint = {
                endpoint: "Dot",
                paintStyle: {
                    stroke: "#888",
                    fill: "#fff",
                    radius: 5,
                    strokeWidth: 1
                },
                /*hoverPaintStyle: endpointHoverStyle,*/
                maxConnections: 1,
                /*cssClass:"in-hover",
                dropOptions: { hoverClass: "in-hover", activeClass: "in-hover" },*/
                isTarget: true,
                overlays: [
                    ["Label", {location: [0.5, -0.5], label: "Drop", cssClass: "endpointTargetLabel", visible: false}]
                ],
                events: {
                    connected: function () {
                        this.setStyle({'display': 'none'});
                        this.setEnabled(false);
                    }
                },
                onMaxConnections: function (info) {
                    //alert("Cannot drop connection " + info.connection.id + " : maxConnections has been reached on Endpoint " + info.endpoint.id);
                }
            };

        var addNode = function (parentId, nodeId, nodeLable, position) {
            var panel = d3.select("#" + parentId);
            var div = panel.append('div')
                .style('position', 'absolute')
                .style('top', position.y).style('left', position.x)
                .attr('align', 'center')
                .attr('id', nodeId).classed('pane-node-content', true);

            div.append('span').classed('iconfont icon-dataBase', true);
            div.append('span').text(nodeLable);
            div.append('span').classed('status icon-warning-o', true);

            /*   var d = document.createElement("div");
             // var id = jsPlumbUtil.uuid();
             d.className = "pane-node-content";
             d.id = nodeId;
             d.innerHTML = nodeLable;
             d.style.left = position.x + "px";
             d.style.top = position.y + "px";
             instance.getContainer().appendChild(d);
     */
            return jsPlumb.getSelector('#' + nodeId)[0];
        }

        var addPorts = function (instance, node, ports, type) {
            //Assume horizental layout
            var number_of_ports = ports.length;
            var i = 0;
            var x_offset = 1 / (number_of_ports + 1);
            var x = 0;

            for (; i < number_of_ports; i++) {
                var anchor = [0, 0, 0, 0];
                var paintStyle = {radius: 5, fill: '#fff', stroke: '#999'};
                var isSource = false, isTarget = false;
                if (type === 'output') {
                    anchor[1] = 1;
                    isSource = true;
                } else {
                    isTarget = true;
                }

                anchor[0] = x + x_offset;
                x = anchor[0];

                instance.addEndpoint(node, isSource ? sourceEndpoint : targetEndpoint, {
                    anchor: anchor, uuid: node.getAttribute("id") + "-" + ports[i]
                });
            }
        }


        // suspend drawing and initialise.
        instance.batch(function () {

            var node1 = addNode('flow-panel', 'node1', '存储过程', {x: '80px', y: '20px'});
            var node2 = addNode('flow-panel', 'node2', 'SQL脚本', {x: '180px', y: '180px'});

            addPorts(instance, node1, ['out1', 'out2'], 'output');
            addPorts(instance, node2, ['in', 'in1', 'in2'], 'input');

            // listen for new connections; initialise them the same way we initialise the connections at startup.
            instance.bind("connection", function (connInfo, originalEvent) {
                // console.log(connInfo.connection.getConnector().canvas)
               connInfo.targetEndpoint.fire('connected');
               $(connInfo.connection.getConnector().canvas).find('path:first').attr('id','p1258');
               addMenu(1,'#p1258');

            });

            // make all the window divs draggable
            instance.draggable(jsPlumb.getSelector(".pane-node-content"));
            // THIS DEMO ONLY USES getSelector FOR CONVENIENCE. Use your library's appropriate selector
            // method, or document.querySelectorAll:
            //jsPlumb.draggable(document.querySelectorAll(".window"), { grid: [20, 20] });

            // connect a few up
            // instance.connect({uuids: ["Window2BottomCenter", "Window3TopCenter"], editable: true});
            // instance.connect({uuids: ["Window2LeftMiddle", "Window4LeftMiddle"], editable: true});
            // instance.connect({uuids: ["Window4TopCenter", "Window4RightMiddle"], editable: true});
            // instance.connect({uuids: ["Window3RightMiddle", "Window2RightMiddle"], editable: true});
            // instance.connect({uuids: ["Window4BottomCenter", "Window1TopCenter"], editable: true});
            // instance.connect({uuids: ["Window3BottomCenter", "Window1BottomCenter"], editable: true});
            //

            //
            // listen for clicks on connections, and offer to delete connections on click.
            //
            // instance.bind("click", function (conn, originalEvent) {
            // if (confirm("Delete connection from " + conn.sourceId + " to " + conn.targetId + "?"))
            //   instance.detach(conn);
            //     conn.toggleType("basic");
            // });

            instance.bind("connectionDrag", function (connection) {
                console.log("connection " + connection.id + " is being dragged. suspendedElement is ", connection.suspendedElement, " of type ", connection.suspendedElementType);
            });

            instance.bind("connectionDragStop", function (connection) {
                console.log(connection)
                console.log("connection " + connection.id + " was dragged");
            });

            instance.bind("connectionMoved", function (params) {
                console.log("connection " + params.connection.id + " was moved");
            });
        });

        jsPlumb.fire("jsPlumbDemoLoaded", instance);


        //Handle drag and drop
        $('ul li').attr('draggable', 'true').on('dragstart', function (ev) {
            //ev.dataTransfer.setData("text", ev.target.id);
            ev.originalEvent.dataTransfer.setData('text', $.trim($(ev.target).text()));
            console.log('drag start');
        });

        $('#flow-panel').on('drop', function (ev) {

            //avoid event conlict for jsPlumb
            if (ev.target.className.indexOf('_jsPlumb') >= 0) {
                return;
            }

            ev.preventDefault();
            var mx = '' + ev.originalEvent.offsetX + 'px';
            var my = '' + ev.originalEvent.offsetY + 'px';

            var text = ev.originalEvent.dataTransfer.getData('text');
            var uid = jsPlumbUtil.uuid();
            var node = addNode('flow-panel', 'node' + uid, text, {x: mx, y: my});
            addPorts(instance, node, ['out'], 'output');
            addPorts(instance, node, ['in1', 'in2'], 'input');

            instance.draggable($(node));

        }).on('dragover', function (ev) {
            ev.preventDefault();
            console.log('on drag over');
        });

        //加载右键菜单
        context.init({preventDoubleContext: false});
    });

    //添加右键菜单
    var addMenu = function(type,obj){

        var param_array = [];
        var idx = 0;
        param_array[idx++] = {header: '区块设置'};

        param_array[idx++] = {text: '删除', action: function(e){
                e.preventDefault();

            }};

        context.attach(obj, param_array);
    }

    $(function(){


    })


</script>
</body>
</html>